<template>
  <PageHeaderWrapper>
    <a-card class="invoicing-theme">
      <a-row>
        <a-col :span="7">
          创建人：
          <a-input class="input-width" placeholder="请输入" v-model="search.createUser"/>
        </a-col>
        <a-col :span="7">
          角色：
          <a-select class="input-width" placeholder="请选择" style="width: 70%" v-model="search.roleName">
            <a-select-option v-for="item in table.roleNameList" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          创建日期：
          <a-date-picker class="input-width" placeholder="请选择日期" v-model="search.createTime"/>
        </a-col>
        <a-col :span="2">
          <a-button type="primary" icon="search" @click="handleRefreshAndSearch">
            搜索
          </a-button>
        </a-col>
        <a-col :span="2">
          <a-button type="primary" :disabled="disabled" @click="handleReset" icon="sync">
            重置
          </a-button>
        </a-col>
      </a-row>
    </a-card>
    <a-card>
      <a-row class="table-operations">
        <a-col :span="2">
          <a-button type="primary" icon="plus" @click="modal.addModalVisable = true">
            添加
          </a-button>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" icon="reload" @click="handleRefreshAndSearch">
            刷新
          </a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-table
          rowKey="id"
          :columns="columns"
          :data-source="table.dataList"
          :loading="table.loading"
          :pagination="table.pagination"
          @change="handleTableChange"
        >
          <template slot="operation" slot-scope="record">
            <a @click="showEditModal(record)">编辑</a>
          </template>
        </a-table>
      </a-row>
    </a-card>
    <div class="modalSpace">
      <a-modal
        title="添加角色"
        width="350px"
        centered
        :visible="modal.addModalVisable"
        :confirm-loading="modal.confirmLoading"
        @ok="handleAddRole"
        @cancel="handleModalClose">
        <a-form :form="form1" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-item label="角色名" has-feedback>
            <a-input
              v-decorator="['roleName', {
                rules: [{ required: true, message: '请输入角色名!' }],
              }]"
            />
          </a-form-item>
          <a-form-item label="描述" has-feedback>
            <a-input
              v-decorator="['description', {
                rules: [{ required: true, message: '请进行描述！' }],
              }]"
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal
        title="编辑角色"
        centered
        width="350px"
        :visible="modal.editModalVisable"
        :confirm-loading="modal.confirmLoading"
        @ok="handleEditRole"
        @cancel="modal.editModalVisable = false">
        <a-form :form="form2" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-form-item label="角色名" has-feedback>
            <a-input
              v-decorator="['roleName', {
                rules: [{ required: true, message: '请输入角色名!' }],
                initialValue: modal.defaultName
              }]"
            />
          </a-form-item>
          <a-form-item label="描述" has-feedback>
            <a-input
              v-decorator="['description', {
                rules: [{ required: true, message: '请进行描述！' }],
                initialValue: modal.defaultDescription
              }]"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </PageHeaderWrapper>
</template>

<script>
import moment from 'moment'
import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import { getRoleTable, addRoleTable, getAllRoleName, updateRoleTable } from '@/api/roleManage'

export default {
  name: 'RoleManage',
  components: {
    PageHeaderWrapper
  },
  computed: {
    columns () {
      return [
        {
          title: '角色名',
          dataIndex: 'roleName',
          align: 'center'
        },
        {
          title: '人数',
          dataIndex: 'count',
          align: 'center'
        },
        {
          title: '描述',
          dataIndex: 'description',
          align: 'center'
        },
        {
          title: '创建人',
          dataIndex: 'createUser',
          align: 'center'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center',
          sorter: true
        },
        {
          title: '操作',
          key: 'operation',
          align: 'center',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    },
    disabled () {
      return !this.search.createUser && !this.search.roleName && !this.search.createTime
    }
  },
  data () {
    return {
      search: {
        createUser: null,
        roleName: null,
        createTime: null
      },
      modal: {
        addModalVisable: false,
        editModalVisable: false,
        defaultId: null,
        defaultName: null,
        defaultDescription: null,
        confirmLoading: false
      },
      form1: this.$form.createForm(this, { name: 'roleAdd' }),
      form2: this.$form.createForm(this, { name: 'roleEdit' }),
      table: {
        roleNameList: [],
        dataList: [],
        sorter: null,
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
          pageSizeOptions: ['10', '15', '20'],
          showTotal: total => `总共 ${total} 条数据`,
          showQuickJumper: true
        },
        loading: false
      }
    }
  },
  created () {
    this.getTableList()
    this.getRoleName()
  },
  methods: {
    handleReset () {
      this.search.createUser = null
      this.search.roleName = null
      this.search.createTime = null
    },
    showEditModal (record) {
      this.modal.defaultId = record.id
      this.modal.defaultName = record.roleName
      this.modal.defaultDescription = record.description
      this.modal.editModalVisable = true
    },
    handleAddRole () {
      this.modal.confirmLoading = true
      const _this = this
      this.form1.validateFields((err, values) => {
        if (!err) {
          addRoleTable({
            roleName: values.roleName,
            description: values.description
          }).then(res => {
            _this.modal.confirmLoading = false
            _this.handleModalClose()
            _this.handleRefreshAndSearch()
            _this.getRoleName()
            _this.$message.success({ content: '添加角色成功' })
          }).catch(err => {
            _this.modal.confirmLoading = false
            _this.$message.error(err.response.data.msg || { content: '添加角色失败' })
          })
        } else {
          setTimeout(() => {
            _this.modal.confirmLoading = false
          }, 600)
        }
      })
    },
    handleModalClose () {
      this.form1.resetFields()
      this.modal.addModalVisable = false
    },
    handleEditRole () {
      const _this = this
      _this.modal.confirmLoading = true
      this.form2.validateFields((err, values) => {
        if (!err) {
          updateRoleTable({
            id: _this.modal.defaultId,
            roleName: values.roleName,
            description: values.description
          }).then(res => {
            _this.modal.confirmLoading = false
            _this.modal.editModalVisable = false
            _this.handleRefreshAndSearch()
            _this.getRoleName()
            _this.$message.success({ content: '修改角色成功' })
          }).catch(err => {
            _this.modal.confirmLoading = false
            _this.$message.error(err.response.data.msg || { content: '修改角色失败' })
          })
        } else {
          setTimeout(() => {
            _this.modal.confirmLoading = false
          }, 600)
        }
      })
    },
    handleRefreshAndSearch () {
      this.table.pagination.current = 1
      this.getTableList()
    },
    handleTableChange (pagination, filters, sorter) {
      this.table.pagination = pagination
      this.table.sorter = sorter
      this.getTableList()
    },
    getRoleName () {
      const _this = this
      getAllRoleName().then(res => {
        _this.table.roleNameList = res.data.roleNameList
      }).catch(err => {
        _this.$message.error(err.response.data.msg)
      })
    },
    getTableList () {
      this.table.loading = true
      const _this = this
      const sorter = _this.table.sorter || {}
      let crt = _this.search.createTime
      if (crt !== null) {
        crt = moment(_this.search.createTime).format('YYYY-MM-DD HH:mm:ss')
      }
      getRoleTable({
        page: _this.table.pagination.current,
        pageSize: _this.table.pagination.pageSize,
        order: sorter.order,
        createUser: _this.search.createUser,
        roleName: _this.search.roleName,
        createTime: crt
      }).then(res => {
        this.table.pagination.total = res.data.total
        this.table.dataList = res.data.list
        this.table.loading = false
      }).catch(err => {
        this.$message.error(err.response.data.msg || '获取数据失败')
        this.table.loading = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.input-width {
  width: 70%;
}

.table-operations {
  margin-bottom: 10px;
}

.delete {
  margin-right: 10px;
}
</style>
